package com.seven.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@SuppressWarnings( "serial" )
public class UserController extends HttpServlet{

  @SuppressWarnings( "unchecked" )
  @Override
  protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException {
    String params = getParamByReq( req );
    Map<String,String> paramMap =  JSON.parseObject( params, Map.class );
    Map<String,String> mp = new HashMap<>();
    mp.put( "id",paramMap.get( "id" ) );
    mp.put( "name", "hello world" );
    String jsonString = JSON.toJSONString( mp );
    System.out.println( "传回前台的数据为---》"+jsonString );
    PrintWriter writer = resp.getWriter();
    writer.write( jsonString );
    writer.flush();
    writer.close();
  }
  
  @Override
  protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException {
    doPost( req, resp );
  }
  /**
   * 从request获取json格式参数
   */
  private String getParamByReq(HttpServletRequest req)throws IOException{
    BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8")); // 实例化输入流，并获取网页代码
    String s =null; // 依次循环，至到读的值为空
    StringBuilder sb = new StringBuilder();
    while ((s = reader.readLine()) != null) {
    sb.append(s);
    }
    reader.close();

    return sb.toString();
  }
}
